from django.contrib.auth.forms import UsernameField
from django.forms import ModelForm, Form
from django.forms import TextInput, PasswordInput, EmailInput
from django.forms import CharField, EmailField
from .models import User


class SignInForm(Form):
    username = UsernameField(widget=TextInput(attrs={'class': 'form-control'}))
    password = CharField(widget=PasswordInput(attrs={'class': 'form-control'}))


class SignUpForm(ModelForm):

    email = EmailField(widget=EmailInput(
        attrs={'class': 'form-control', 'id': 'email'}))
    username = UsernameField(widget=TextInput(attrs={'class': 'form-control'}))
    password = CharField(widget=PasswordInput(attrs={'class': 'form-control'}))

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            self.add_error('email', "邮箱已存在!")
        return email

    def clean_username(self):
        username = self.cleaned_data['username']
        if len(username) < 4:
            self.add_error('username', "用户名长度至少为4!")
        if User.objects.filter(username=username).exists():
            self.add_error('username', "用户名已存在!")
        return username

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data["password"])
        user.balance = 100.0
        if commit:
            user.save()
        return user

    class Meta:
        model = User
        fields = ["username", "email"]
